package dao;

import org.junit.Test;
import pojo.User;
import utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author konley
 * @date 2020-06-17 15:38
 */
public class UserDao {
    //判断用户名是否存在
    public static boolean checkName(String name){
        Connection con = DBUtils.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            ps =con.prepareStatement("select * from user where name=?");
            ps.setString(1,name);
            rs = ps.executeQuery();
            if(rs.next())
                return false;
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBUtils.release(rs,ps,con);
        }
        return true;
    }

    //注册
    public static boolean addUser(User user){
        Connection con = DBUtils.getConnection();
        PreparedStatement ps = null;
        try{
            ps =con.prepareStatement("insert into user value(?,?,?,?)");
            ps.setString(1,user.getName());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getTel());
            ps.setString(4,user.getAddress());
            return ps.execute();

        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBUtils.release(ps,con);
        }
        return false;
    }

    //根据id获取用户类
    public static User getUserByName(String name){
        User user = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Connection con = DBUtils.getConnection();
        try {
            ps = con.prepareStatement("select * from user where name=?");
            ps.setString(1,name);
            System.out.println(ps);
            rs = ps.executeQuery();
            if(rs.next()){
                user = new User(
                        rs.getString("name"),
                        rs.getString("password"),
                        rs.getString("tel"),
                        rs.getString("address")
                );
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBUtils.release(rs,ps,con);
        }
        return user;
    }

}
